package com.sxt.core.provider.listener;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.sxt.core.anno.AutoBuilder;
import com.sxt.core.anno.Inject;
import com.sxt.core.codc.Codecer;
import com.sxt.core.model.Request;
import com.sxt.core.model.Response;
import com.sxt.core.net.NetServerService;
import com.sxt.core.provider.InvokeLocalMethod;
import com.sxt.core.util.ResourceUtil;
import com.sxt.core.util.ThreadLocalUtil;

@AutoBuilder
public class ListenerServer {

	@Inject
	private NetServerService netService;

	@Inject
	private Codecer coderer;
	
	@Inject
	private InvokeLocalMethod methodExecuter;

	public  void listener(int port) {
		netService.bind(port);// 绑定端口
		while(true) {
			InputStream inputStream = null ;
			OutputStream outputStream = null ; 
			try {
				
				// 获取输入资源
				inputStream = netService.getInputStream();
				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				byte []bs = new byte[2048];
				int len = 0 ;
				while((len=inputStream.read(bs))!=-1) {
					if(bs[len-1]!=-1) {
						byteArrayOutputStream.write(bs, 0, len); // 正常的写
					}else { //[1,2,-1]    [-1]
						if(len==1) { // 读最后一轮了，最后一个刚好是-1
							break ;
						}else {
							// 读最后一轮了，但是最后的还有有效数据，先把 有效数据读取出来
							byteArrayOutputStream.write(bs, 0, len-1);
							break ;
						}
						
					}
				}
				byte[] byteArray = byteArrayOutputStream.toByteArray(); // Reuqest
				Request request = (Request)coderer.deCode(byteArray);
			
				// 执行本地的调用
				Response result = methodExecuter.execute(request) ;
				
				//编码
				byte[] respBytes = coderer.code(result);
				// 发送数据的操作
				byte[]respBytesTotal = new byte[respBytes.length+1];//  length + 1 = -1
				System.arraycopy(respBytes, 0, respBytesTotal, 0, respBytes.length);
				respBytesTotal[respBytesTotal.length-1] = -1;  // 结束的标签
				//
				
				//输出开始
				outputStream = netService.getOutputStream();
				outputStream.write(respBytes);
				outputStream.flush();
				// 输出完毕
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				// 清空线程资源
				ThreadLocalUtil.clearValue();
				ResourceUtil.closes(outputStream,inputStream);
			}
		}
	}
}
